
package commonlib.persistance;

import java.util.*;
import java.io.*;
import commonlib.domain.Text;
import commonlib.domain.TxtWord;

/**
 *
 * @ Marti.Nogue
 */

public class TextDataManager
{
    // VARIABLES: --------------------------------------------------------------

    private File file;

    private Scanner input;

    // CONSTRUCTOR: ------------------------------------------------------------

    public TextDataManager(String path)
    {
        this.file = new File(path);
    }

    // PUBLIC METHODS: ---------------------------------------------------------

    public Text load()
    {
        Text text = new Text();

        try
        {
            FileReader reader = new FileReader(file.getPath());

            BufferedReader inputStream = new BufferedReader(reader);

            String inLine = null;
            while ((inLine = inputStream.readLine()) != null)
            {
                text.addWord(inLine);
            }

            inputStream.close();
        }
        catch (IOException e)
        {
            System.out.println("IOException:");
            e.printStackTrace();
        }

        return text;
    }

    public void saveNext(Text text)
    {
        ArrayList<TxtWord> textArray = new ArrayList<TxtWord>();
        for (int i = 0; i < text.getsize(); ++i)
        {
            textArray.add(text.getWord(i));
        }

        Iterator<TxtWord> it = textArray.iterator();

        try
        {
            FileWriter writer = new FileWriter(this.file);
            BufferedWriter buffer = new BufferedWriter(writer);

            while (it.hasNext() )
            {
                TxtWord txtWord = it.next();
                buffer.write(txtWord.getWord()+" ");
            }
            buffer.close();
        }
        catch (IOException e)
        {
            System.out.println("IOException:");
            e.printStackTrace();
        }
    }

    public void saveReplace(Text text)
    {
        removeFile();
        saveNext(text);
    }

    public void removeFile()
    {
        file.delete();
    }

    // PRIVATE METHODS: --------------------------------------------------------

    private void closeFile()
    {
        input.close();
    }
}